I need a regular expression which validate the floating point number, I have build the following.
<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^-0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/(\-.*)\-/g, '$1');" />
It works but it fails in case of 11-111. How to I fix it.
Maybe something like this:
const validateFloat = (e) => {
let val = e.currentTarget.value;
if(isNaN(val)){
val = val.replace(/[^-0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
e.currentTarget.value = val;
}
Using:
input.addEventListener("input", validateFloat);
Working with negative values too.
You can use this this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1') like:
<label for="salary">Enter floating nunmber:</label>
<input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')" />
The sort of input validation you are trying here is going to be monstrous in a single regEx so you would be better off breaking it into several smaller ones
/[^0-9-.]/g to remove any none valid characters/(-.*)-/g to remove any extra -/(\..*)\./g to remove any extra .this would look like this
let val = '-abc123.45.67-89';
val = val.replace(/[^0-9-.]/g, '');
val = val.replace(/(-.*?)-/g, '$1');
val = val.replace(/(\..*?)\./g, '$1');
console.log(val)
//"-123.456789"
if you are performing this on every char input then this should work fine however on bulk entry (ie a paste) you may need to loop the replaces to take into account that previous matches wont be included in the next match
eg
let val = '-123-abc.123.45.67-89';
val = val.replace(/[^0-9-.]/g, '');
const minusMatch = /(-.*?)-/g;
while(val.search(minusMatch)>=0){
val = val.replace(minusMatch, '$1');
}
const dotMatch = /(\..*?)\./g;
while(val.search(dotMatch)>=0){
val = val.replace(dotMatch, '$1');
}
console.log(val)